<template>
  <div class="container">
    <OrderBar :username="userInfo.userName" :order="serviceNo"></OrderBar>
    <div class="content">
      <van-form ref="form" class="form">
        <van-field
          v-model="form.serviceDate"
          name="serviceDate"
          clickable
          readonly
          label="服务日期"
          required
          :rules="rules.serviceDate"
          placeholder="点击服务日期"
          @click="openCalendar('serviceDate', null, 'YYYY年MM月DD日')"
        />

        <van-field
          v-model="form.maintainPartsName"
          name="maintainParts"
          clickable
          readonly
          label="维修部件"
          type="textarea"
          required
          :rules="rules.maintainParts"
          placeholder="点击维修部件"
          @click="openPickerMul('maintainParts', form,maintainPartsNameChange)"
        />

        <van-field
          v-model="form.maintainPartsInfoName"
          name="maintainPartsInfo"
          clickable
          readonly
          label="部件问题"
          type="textarea"
          required
          :rules="rules.maintainPartsInfo"
          placeholder="点击部件问题"
          @click="getMaintainPartsInfoList"
        />

        <van-field
          v-model="form.winfanConfigName"
          name="winfanConfig"
          clickable
          readonly
          label="风机配置"
          required
          :rules="rules.winfanConfig"
          placeholder="点击风机配置"
          @click="openPicker('winfanConfig')"
        />

        <van-field
          v-model="form.applyIndustryName"
          name="applyIndustry"
          clickable
          readonly
          required
          :rules="rules.applyIndustryName"
          label="使用行业"
          placeholder="点击使用行业"
          @click="openPicker('applyIndustry')"
        />

        <van-field
          v-model="form.serviceResult"
          label="处理结果"
          name="serviceResult"
          rows="1"
          autosize
          required
          :rules="rules.serviceResult"
          type="textarea"
          maxlength="500"
          show-word-limit
          placeholder="请输入处理结果"
        />

        <van-field
          v-model="form.contactPost"
          name="contactPost"
          rows="1"
          autosize
          label="客户职务"
          required
          :rules="rules.contactPost"
          type="text"
          placeholder="请输入客户职务"
        />
        <van-field
          v-model="form.estimateName"
          name="estimate"
          clickable
          readonly
          required
          :rules="rules.estimate"
          label="客户评价"
          placeholder="点击客户评价"
          @click="openPicker('estimate')"
        />
        <van-field
          v-model="form.workHours"
          name="workHours"
          type="number"
          required
          :rules="rules.workHours"
          label="实际工时"
          placeholder="请输入实际工时"
        />

        <van-field
          v-model="form.responsibilityName"
          name="responsibility"
          clickable
          readonly
          label="责任归属"
          required
          :rules="rules.responsibility"
          placeholder="点击责任归属"
          @click="openPickerMul('responsibility')"
        />

        <van-field
          v-model="form.serviceNatureName"
          name="serviceNature"
          clickable
          readonly
          required
          :rules="rules.serviceNature"
          label="服务性质"
          placeholder="点击服务性质"
          @click="openPicker('serviceNature')"
        />

        <van-field
          name="secondMaintain"
          required
          :rules="rules.secondMaintain"
          label="二次维护"
        >
          <template #input>
            <van-radio-group
              v-model="form.secondMaintain"
              direction="horizontal"
            >
              <van-radio
                name="01"
                shape="square"
              >是
              </van-radio>
              <van-radio
                name="00"
                shape="square"
              >否
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field
          v-if="form.secondMaintain === '01'"
          v-model="form.secondMaintainReason"
          name="secondMaintainReason"
          rows="1"
          autosize
          label="维修原因"
          type="text"
          placeholder="请输入维修原因"
        />

        <van-field
          v-model="form.feeBelongName"
          name="feeBelong"
          label="费用归属"
          clickable
          readonly
          required
          type="textarea"
          :rules="rules.feeBelong"
          placeholder="点击费用归属"
          @click="openPickerMul('feeBelong')"
        />

        <van-field
          v-if="form.feeBelong.includes('99')"
          v-model="form.feeBelongOrder"
          name="feeBelongOrder"
          rows="1"
          autosize
          required
          :rules="rules.feeBelongOrder"
          label="合约单号"
          type="text"
          placeholder="请输入合约单号"
        />

        <van-field
          v-model="form.feeBelongRemark"
          name="feeBelongRemark"
          required
          :rules="rules.feeBelongRemark"
          autosize
          label="费用定性"
          type="textarea"
          placeholder="请输入费用定性"
        />

        <van-field
          name="doorPic"
          required
          :rules="rules.doorPic"
          label="厂门照片"
        >
          <template #input>
            <van-uploader
              v-model="form.doorPicObj"
              :max-count="1"
              :after-read="file => afterUpload(file, 'doorPic')"
              @delete="form.doorPic = ''"
            />
          </template>
        </van-field>

        <van-field
          name="winFanPic"
          label="风机铭牌"
          :required="!form.noPic"
          :rules="rules.winFanPic"
        >
          <template #input>
            <van-uploader
              v-model="form.winFanPicObj"
              :max-count="1"
              :after-read="file => afterUpload(file, 'winFanPic')"
              :disabled="form.noPic"
              @delete="form.winFanPic = ''"
            />
            <van-checkbox
              v-model="form.noPic"
              shape="square"
              @click="handleNoPic"
            >厂区禁止拍照
            </van-checkbox>
          </template>
        </van-field>

        <van-field
          name="sceneFiles"
          label="其他照片"
        >
          <template #input>
            <van-uploader
              v-model="form.sceneFilesObj"
              multiple
              :after-read="file => afterUploadMul(file, 'sceneFiles')"
              @delete="removePic"
            />
          </template>
        </van-field>

        <van-field
          v-model="form.saleDate"
          name="saleDate"
          clickable
          readonly
          label="出厂日期"
          required
          :rules="rules.saleDate"
          placeholder="点击出厂日期"
          @click="openDatetimePicker('saleDate', null, 'YYYY年MM月')"
        />

        <van-field
          v-model="form.winFanNum"
          name="winFanNum"
          type="number"
          label="风机数量"
          required
          :rules="rules.winFanNum"
          placeholder="请输入风机数量"
        />
        <!--        <van-field-->
        <!--          v-model="form.useDate"-->
        <!--          name="useDate"-->
        <!--          type="number"-->
        <!--          label="使用时间"-->
        <!--          required-->
        <!--          :rules="rules.useDate"-->
        <!--          placeholder="请输入使用时间"-->
        <!--        />-->

        <van-calendar
          v-model="showCalendar"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="onConfirmCalendar"
        />

        <van-popup
          v-model="showDatetimePicker"
          position="bottom"
        >
          <van-datetime-picker
            v-model="currentDate"
            type="year-month"
            title="选择日期"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="onConfirmDatetimePicker"
            @cancel="onCancelDatetimePicker"
          />
        </van-popup>

        <van-popup
          v-model="showPicker"
          position="bottom"
        >
          <van-picker
            show-toolbar
            :columns="currentOptions"
            value-key="label"
            @confirm="onConfirmPicker"
            @cancel="showPicker = false"
          >
            <van-search
              v-if="currentOptionsCache.length>showSearchMaxOptionsLength"
              slot="title"
              v-model="pickerKeyword"
              placeholder="快速搜索"
              shape="round"
              @input="filterCurrentOptions"
            />
          </van-picker>

        </van-popup>

        <van-popup
          v-model="showPickerMul"
          position="bottom"
        >
          <div class="van-picker">
            <div class="van-picker__toolbar">
              <button class="van-picker__cancel" @click="onCancelPickerMul">取消</button>
              <button class="van-picker__confirm" @click="onConfirmPickerMul">确认</button>
            </div>
          </div>

          <div class="van-picker__columns multiple-box">
            <div class="van-picker-column">
              <van-checkbox-group v-model="checkBoxMul">
                <van-cell v-for="(v, i) in currentOptions" :key="i" :title="`${v.label}`">
                  <template #right-icon>
                    <van-checkbox shape="square" :name="v.value" />
                  </template>
                </van-cell>
              </van-checkbox-group>
            </div>
          </div>
        </van-popup>

        <div class="btns">
          <van-button
            v-if="form.archiveStatus !== '02'"
            type="primary"
            size="small"
            icon="clock"
            @click="save('/saleService/stagingSaleServiceArchive')"
          >暂存
          </van-button>
          <van-button
            type="warning"
            size="small"
            icon="checked"
            @click="submit('/saleService/submitSaleServiceArchive')"
          >{{ form.archiveStatus === "02" ? "更新" : "提交" }}
          </van-button>
          <van-button
            type="danger"
            size="small"
            icon="clear"
            @click="close"
          >关闭
          </van-button>
        </div>
      </van-form>

    </div>
  </div>
</template>

<script>
import OrderBar from '../../components/OrderBar'
import dayjs from 'dayjs'
import { urlParams } from '@/assets/utils'
import { form, userInfo } from '@/assets/utils/mixin'

export default {
  components: { OrderBar },
  mixins: [ userInfo, form ],
  data() {
    const ruleKeys = [
      'serviceDate',
      'maintainParts',
      'maintainPartsInfo',
      'winfanConfig',
      'applyIndustry',
      'applyIndustryName',
      'serviceResult',
      'contactPost',
      'estimate',
      'workHours',
      'responsibility',
      'responsibilityName',
      'serviceNature',
      'serviceNatureName',
      'secondMaintain',
      // 'secondMaintainReason',
      'feeBelong',
      'feeBelongOrder',
      'feeBelongRemark',
      'doorPic',
      'winFanPic',
      // 'sceneFiles',
      'saleDate',
      'winFanNum',
      // 'useDate',
    ]
    const rules = {}
    ruleKeys.forEach(key => rules[key] = [ { required: true } ])
    rules.secondMaintain[0].message = '请选择二次维护'
    rules.feeBelong[0].message = '请选择费用归属'
    rules.doorPic[0].message = '请选择厂门照片'
    rules.winFanPic[0].message = '请选择风机铭牌'
    rules.winFanPic[0].required = false
    // rules.sceneFiles[0].message = '请选择其他照片'

    return {
      serviceNo: urlParams.get('serviceNo'),

      form: {
        saleServiceId: urlParams.get('saleServiceId'),
        archiveNo: urlParams.get('archiveNo'),

        serviceDate: '',
        maintainParts: '',
        maintainPartsName: '',
        maintainPartsInfo: '',
        maintainPartsInfoName: '',
        winfanConfig: '',
        winfanConfigName: '',
        applyIndustry: '',
        applyIndustryName: '',
        serviceResult: '',
        contactPost: '',
        estimate: '',
        workHours: '',
        responsibility: '',
        responsibilityName: '',
        serviceNature: '',
        serviceNatureName: '',
        secondMaintain: '',
        secondMaintainReason: '',

        feeBelong: '',
        feeBelongName: '',
        feeBelongOrder: '',
        feeBelongRemark: '',
        doorPic: '',
        doorPicObj: [],
        winFanPic: '',
        winFanPicObj: [],
        sceneFiles: [],
        sceneFilesObj: [],
        saleDate: '',
        winFanNum: '',
        // useDate: null,
        noPic: false, // 禁止拍照

      },

      options: {
        applyIndustry: null,
        responsibility: [
          { label: '客户', value: '10' },
          { label: '生产中心', value: '11' },
          { label: '供应商', value: '12' },
          { label: '物流中心', value: '13' },
          { label: '业务', value: '14' },
          { label: '售后', value: '15' },
          { label: '开发部', value: '16' },
          { label: '总营', value: '17' },
        ],
        serviceNature: [
          { label: '无偿服务', value: '03' },
          { label: '有偿服务', value: '04' },
        ],
        feeBelong: [
          { label: '计生产', value: '01' },
          { label: '计开发', value: '02' },
          { label: '计供应商', value: '03' },
          { label: '计物流', value: '04' },
          { label: '计业务', value: '05' },
          { label: '计订单', value: '06' },
          { label: '计售后', value: '07' },
          { label: '计总营', value: '08' },
          { label: '计合约', value: '99' },
        ],

        estimate: [
          { label: '很满意', value: '01' },
          { label: '满意', value: '02' },
          { label: '一般', value: '03' },
          { label: '不满意', value: '04' },
          { label: '很不满意', value: '05' },
        ],

        maintainParts: [
          { label: '更换配件', value: '01' },
          { label: '叶轮', value: '02' },
          { label: '壳体', value: '03' },
          { label: '隔音箱', value: '04' },
          { label: '传动组', value: '05' },
          { label: '轴', value: '06' },
          { label: '外观', value: '07' },
          { label: '性能', value: '08' },
          { label: '电控', value: '09' },
          { label: '补偿器', value: '10' },
          { label: '其它', value: '99' },
        ],

        winfanConfig: [
          { label: '前送', value: '01' },
          { label: '后抽', value: '02' },
          { label: '其他', value: '03' },
        ],

        maintainPartsInfo: [],

      },
      rules,

    }
  },
  computed: {},
  watch: {
  },
  created() {
    this.init()
  },
  mounted() {
  },
  methods: {
    init() {
      this.getUserInfo()
      this.getIndustryOptions()
      this.getArchiveNo()
    },

    async afterUpload(file, key) {
      const fileRes = await this.upload(file)
      this.form[key] = fileRes.attachName
    },
    async afterUploadMul(fileList, key) {
      if (!Array.isArray(fileList)) fileList = [ fileList ]
      Promise.all(fileList.map(file => this.upload(file))).then(res => {
        this.form[key].push(...res.map(e => ({ ...e, url: e.attachName })))
      })
    },

    async getArchiveNo() {
      // 这个需要通过结案单号来查询  不能拿id去查 没有结算单号说明是新增
      if (!this.form.archiveNo) return
      const res = await this.server.get('/saleService/findSaleServiceArchiveByArchiveNo', {
        archiveNo: this.form.archiveNo,
      })
      if (res.code === '0') {
        this.form.uuid = res.object?.uuid
        for (const key in this.form) {
          if (res.object[key]) this.form[key] = res.object[key]
        }
        // 处理 服务性质
        this.form.serviceNatureName = this.options.serviceNature.find(e =>
          e.value === this.form.serviceNature,
        )?.label || ''

        this.form.estimateName = this.options.estimate.find(e =>
          e.value === this.form.estimate,
        )?.label || ''

        // 处理费用归属
        this.form.feeBelongName = this.options.feeBelong
          .filter(e => this.form.feeBelong.includes(e.value))
          .map(e => e.label).join(',')

        this.form.maintainPartsName = this.options.maintainParts
          .filter(e => this.form.maintainParts.includes(e.value))
          .map(e => e.label).join(',')

        this.form.maintainPartsInfoName = this.form.maintainPartsInfo // 特殊处理

        // 处理图片
        if (this.form.doorPic) {
          this.form.doorPicObj = [ { url: this.form.doorPic, isImage: true } ]
          this.form.doorPic = this.form.doorPic.split('upload/')[1]
        }
        if (this.form.winFanPic) {
          this.form.winFanPicObj = [ { url: this.form.winFanPic, isImage: true } ]
          this.form.winFanPic = this.form.winFanPic.split('upload/')[1]
        }
        this.form.noPic = !this.form.winFanPic
        if (this.form.sceneFiles) {
          this.form.sceneFilesObj = this.form.sceneFiles.map(e => ({ ...e }))
          this.form.sceneFiles.forEach(e => e.url = e.attachName)
        } else {
          this.form.sceneFiles = []
        }
      }
    },

    // 获取使用行业下拉选项
    async getIndustryOptions() {
      const res = await this.server.get('/saleService/getIndustryList')
      if (res.code === '0') {
        this.options.applyIndustry = res.object.map(e => ({ label: e.name, value: e.value }))
      }
    },

    handleNoPic() {
      this.rules.winFanPic[0].required = !this.form.noPic
    },

    removePic(data) {
      this.form.sceneFiles.splice(
        this.form.sceneFiles.findIndex(e => e.attachName === data.attachName), 1)
    },

    async getMaintainPartsInfoList() {
      const res = await this.server.get('/saleService/selectByMaintainParts', {
        maintainParts: this.form.maintainParts,
      })
      this.options.maintainPartsInfo = res.map(e => e.children)
        .flat()
        .map(e => ({ label: e.name, value: e.value }),
        )
      this.openPickerMul('maintainPartsInfo')
    },

    maintainPartsNameChange() {
      this.form.maintainPartsInfo = ''
      this.form.maintainPartsInfoName = ''
    },

  },
}
</script>

<style lang="less" scoped>
@import "../../assets/var";

.container {
  width: 100%;
  height: 100%;
  background: #f8f8f8;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  position: relative;

  > div {
    width: 100%;
  }

  .content {
    position: relative;
    flex: 1;
    background: #f8f8f8;

    .form {
      margin-bottom: 100px;
      width: 100%;
      min-height: calc(100% - 56px);

      .costCheckbox {
        ::v-deep .van-checkbox {
          margin-bottom: 8px;
        }
      }

      .btns {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        display: flex;
        justify-content: space-evenly;
        align-items: center;
        margin-bottom: 30px;
        .safe-margin();
      }
    }
  }
}
</style>
